$m(function(args) {
	var $form = $('#dialog-casebase-tempo').find('form');
	var that = this;
	var $this = this.element;
	// var id = args.fileName;  //成果code
	var id= "";
	//成果信息
	var appInfo;
	//当前成果权限
	var auths;
	var originalAuths;
	var commentStatus = false;
	if(args != undefined){
		id = args.fileName;
	}

	var init = function(){
		Eventbus.one("builPermissionData.mine", builPermissionData);
        Eventbus.bind("renderPage.mine", renderPage);
        Eventbus.bind("initEvent.mine", initEvent);
		// initEvent();
		// renderPage();
	};

	/**
	 * 	清理页面状态至初始状态
	 */
	var clearPageStatus = function(){
		appInfo = undefined;
		auths = undefined;
		originalAuths = undefined;
		commentStatus = false;
		$this.find("#tempo-app-permission-comment").prop("checked", false);
		$this.find(".tempo-app-permission-type-complete").removeClass("tempo-app-permission-type-complete");
		$this.find(".tempo-app-permission-type-container").empty();
		$this.find(".tempo-appp-permission-type-menu-tip").removeClass("tempo-appp-permission-type-menu-tip");
		$this.find(".tempo-app-permission-type-search").searchbar("setValue","");


	}

	var renderPage = function(){
		if(args == undefined){
			id =  $form.find("#code").val();
		}else{
			$form.find("#code").val(id);
		}
        loadAchievement(id, function(data){
            appInfo = data;
            loadPermission(id, function(data){
                auths = tidyPermission(data);
                originalAuths = TempoUtils.clone(auths);
                permissionTypeTabMark(auths);
                //若有选中的展示选中的，无则第一个
                var selected = $this.find(".tempo-app-permission-type-menu li.tempo-app-permission-type-menu-selected");
                if(selected.length>0){
                    $this.find(".tempo-app-permission-type-menu li.tempo-app-permission-type-menu-selected").trigger("click");
                }else{
                    $this.find(".tempo-app-permission-type-menu :first-child").trigger("click");
                }
            });
        })

	}


	var initEvent = function(){
		//各类型搜索框
		$this.find("#tempo-app-permission-type-org .tempo-app-permission-type-search").searchbar({
			width: 200,
			useRadius: true,
			isEnter: true,
			placeholder: getI18n("please_input_name"),
			onSearch: function(text){
				updateAuths(getModifiedAuths("3"), "org");
				renderTree("3", text);
			}
		});
		$this.find("#tempo-app-permission-type-role .tempo-app-permission-type-search").searchbar({
			width: 200,
			useRadius: true,
			isEnter: true,
			placeholder: getI18n("please_input_name"),
			onSearch: function(text){
				updateAuths(getModifiedAuths("4"), "role");
				renderTree("4", text);
			}
		});
		$this.find("#tempo-app-permission-type-group .tempo-app-permission-type-search").searchbar({
			width: 200,
			useRadius: true,
			isEnter: true,
			placeholder: getI18n("please_input_name"),
			onSearch: function(text){
				updateAuths(getModifiedAuths("5"), "group");
				renderTree("5", text);
			}
		});
		$this.find("#tempo-app-permission-type-user .tempo-app-permission-type-search").searchbar({
			width: 200,
			useRadius: true,
			isEnter: true,
			placeholder: getI18n("please_input_name_username"),
			onSearch: function(text){
				updateAuths(getModifiedAuths("6"), "user");
				renderTree("6", text);
			}
		});
		$this.find("#tempo-app-permission-type-user-onlyauth").change(function(){
			$this.find("#tempo-app-permission-type-user .tempo-app-permission-type-search").searchbar('clear',false);
			$this.find("#tempo-app-permission-type-user .tempo-app-permission-type-search")
				.find(".tempo-ui-icon-search-clean").css("display", "none");
			updateAuths(getModifiedAuths("6"), "user");
			renderTree("6", "");
		});
		//$this.find("#Pagination").pagination("15");
		//权限类型tab菜单
		var content = $this.find(".tempo-app-permission-content");
		$this.find(".tempo-app-permission-type-menu").on("click", "li", function(event){
			var li = $(this);
			var href = li.attr("href");
			li.parent().children().removeClass("tempo-app-permission-type-menu-selected");
			li.addClass("tempo-app-permission-type-menu-selected");
			content.find(".tempo-app-permission-type-content").hide();
			content.find(href).show();
			if (!li.hasClass("tempo-app-permission-type-complete")) {
				loadTypePermission(href);
				li.addClass("tempo-app-permission-type-complete");
			}
		});
	}

	var viewUser = function(data){
		var dialog = $("<div>").addClass("tempo-app-permission-view-user");
		var table = $("<table>").appendTo(dialog);
		var url = "/cloud-system-manage/api/ou/emp/listEmp";
		var postData = {
			id: data.id,
			progeny: true,
			part: true
		};
		if (data.type == "role") {
			url = "/cloud-system-manage/api/ou/emp/list-by-role";
			postData = {
				id: data.id
			};
		} else if(data.type == "workgroup"){
			url = "/cloud-system-manage/api/ou/emp/list-by-workgroup";
			postData = {
				id: data.id
			};
		}

		var renderGrid = function(){
			table.datagrid({
				url : url,
				datatype:'json',
				fit:true,
				rownumbers : true,
				colNames:[getI18n("user_name"), getI18n("code"), getI18n("user_org")],
				colModel:[{
					name:'name'
				},{
					name:'code'
				},{
					name:'deptName'
				}],
				pagination:true,
				multiselect : false,
				postData: postData,
				searchBar:true,
				jsonReader : {
					root:"data.rows",page:"data.page",total:"data.totalPages",records:"data.total"
				},
				searchBarOptions:{
					placeholder: getI18n("please_input_name_code"),
					onSearch:function(value){
						table.datagrid("reloadGrid", {name:value}, true);
					},
					useRadius:false
				},
				toolbar:[]
			});
		}
		dialog.dialog({
			title: getI18n("insights_user"),
			width: 638,
			height: 460,
			resizable: false,
			modal: true,
			close: function(){
				dialog.remove();
			},
			open: function(){
				renderGrid();
			},
			buttons: [{
				text: getI18n("close"),
				click: function(){
					dialog.dialog("close");
				}
			}]
		})
	}

	var loadTypePermission = function(href){
		var type = href.split("-").pop();
		switch (type) {
		case "org":
			renderTree("3", "");
			break;
		case "role":
			renderTree("4", "");
			break;
		case "group":
			renderTree("5", "");
			break;
		case "user":
			renderTree("6", "");
			break;
		default:
			break;
		}
	}

	var renderTree = function(authType, text){
		//获取根组织机构Id
		var rootOrgId = $form.find("#rootOrgId").val();
		var href = "#tempo-app-permission-type-";
		var options = {
			langType : contextLocale,
			authType : authType,
			viewCallback: function(data){
				viewUser(data);
			}
		};
		if (authType == "3") {
			href += "org";
			options.url = "/cloud-system-manage/api/ou/org/tree-tempo";
			options.param = {
				id: rootOrgId,
				origin: true
			};
			options.authData = auths.org;
		} else if(authType == "4"){
			href += "role";
			options.url = "/cloud-system-manage/api/ou/role/tree-tempo";
			options.param = {
				id: rootOrgId,
				origin: true
			};
			options.authData = auths.role;
			options.isLeaf =  function(data){
				return data.type == "role";
			};
			options.operate = function(data){
				return data.type == "role";
			};
		} else if(authType == "5"){
			href += "group";
			options.url = "/cloud-system-manage/api/ou/workgroup/tree-tempo"; //获取工作组树  sysRoleCode: SYS_AI_SJRY
			options.param = {
				id: rootOrgId,
				origin: true
			};
			options.authData = auths.group;
			options.isLeaf =  function(data){
				return data.type == "workgroup";
			};
			options.operate = function(data){
				return data.type == "workgroup";
			};
		} else if(authType == "6"){
			href += "user";
			if ($this.find("#tempo-app-permission-type-user-onlyauth").is(":checked")) {
				options.url = contextPath + "/api/ai/resource/permission/user-list";
				options.param = {
					code: id,
					page: 1,
					rows: 10
				};
			} else {
				options.url = "/cloud-system-manage/api/ou/emp/listEmp"; //获取人员
				options.param = {
					id: rootOrgId,
					progeny: true,
					part: true,
					page: 1,
					rows: 10
				};
			}
			options.isPagination = true;
			options.beforePaging = function(){
				updateAuths(getModifiedAuths("6"), "user");
				this.options.authData = auths.user;
			}
			options.authData = auths.user;
			options.isLeaf =  function(data){
				return true;
			};
			options.operate = function(data){
				return true;
			};

		}
		if (text != "") {
			options.param.progeny = true;
			options.param.name = text;
			options.expand = false;
			options.nodeLimit = 200;
			options.isLeaf =  function(data){
				return true;
			};
		}
		var container = $this.find(href).find(".tempo-app-permission-type-container").empty();
		$("<div>").appendTo(container).altree(options);
	}

	/**
	 * 修改权限
	 * @param authType
	 */
	var getModifiedAuths = function(authType){
		var href = "#tempo-app-permission-type-";
		if (authType == "3") {
			href += "org";
		} else if(authType == "4"){
			href += "role";
		} else if(authType == "5"){
			href += "group";
		} else if(authType == "6"){
			href += "user";
		}
		var tree = $(href).find(".tempo-app-permission-type-container .tempo-app-list-tree");
		return tree.altree("getModifiedAuths");
	}

	/**
	 * 更新权限
	 * @param mAuths
	 * @param type
	 */
	var updateAuths = function(mAuths, type){
		var item, objId;
		for (var i = 0; i < mAuths.length; i++) {
			item = mAuths[i];
			objId = item.objId;
			auths[type][objId] = item;
		}
	}

	/**
	 * 加载案例信息
	 */
	var loadAchievement = function(id, callback){
		var that = this;
		callback.call(that, "");
		var process = $("<div/>").tempoprogressbar();
		$.ajax({
			url:contextPath + '/api/ai/resource/template/get',
			data:{
				"id": id,
				"a": (new Date()).getTime()
			},
			type:'get',
			complete: function(XMLHttpRequest, textStatus){
				process.tempoprogressbar("destroy");
			},
			success:function(resultData){
				if(resultData.success){
					callback.call(that, resultData.data);
				}else{
					$("<div/>").alert({
						width: 500,
						height: 197,
						msg:resultData.message
					});
				}
			}
		});
	}

	var loadPermission = function(id, callback){
		var that = this;
		var process = $("<div/>").tempoprogressbar();
		$.ajax({
			url:contextPath + '/api/ai/resource/permission/list',
			data:{
				"code": id 	,
				"a": (new Date()).getTime()
			},
			type:'get',
			complete: function(XMLHttpRequest, textStatus){
				process.tempoprogressbar("destroy");
			},
			success:function(resultData){
				if(resultData.success){
					callback.call(that, resultData.data);
				}else{
					$("<div/>").alert({
						width: 500,
						height: 197,
						msg:resultData.message
					});
				}
			}
		});
	}

	var tidyPermission = function(data){
		var auths = {
			org: {},
			role: {},
			group: {},
			user: {},
			anon: {}
		};
		var item;
		for (var i = 0; i < data.length; i++) {
			item = data[i];
			switch (item.objType) {
			case '3':
				auths.org[item.objId] = item;
				break;
			case '4':
				auths.role[item.objId] = item;
				break;
			case '5':
				auths.group[item.objId] = item;
				break;
			case '6':
				auths.user[item.objId] = item;
				break;
			case '100':
				auths.anon = item;
				break;
			default:
				break;
			}
		}
		return auths;
	}

	var permissionTypeTabMark = function(auths){
		//组织
		if (Object.keys(auths.org).length > 0) {
			$this.find(".tempo-app-permission-type-menu li[href='#tempo-app-permission-type-org']").addClass("tempo-appp-permission-type-menu-tip");
		}
		//角色
		if (Object.keys(auths.role).length > 0) {
			$this.find(".tempo-app-permission-type-menu li[href='#tempo-app-permission-type-role']").addClass("tempo-appp-permission-type-menu-tip");
		}
		//工作组
		if (Object.keys(auths.group).length > 0) {
			$this.find(".tempo-app-permission-type-menu li[href='#tempo-app-permission-type-group']").addClass("tempo-appp-permission-type-menu-tip");
		}
		//人员
		if (Object.keys(auths.user).length > 0) {
			$this.find(".tempo-app-permission-type-menu li[href='#tempo-app-permission-type-user']").addClass("tempo-appp-permission-type-menu-tip");
		}
	}


	var builPermissionData = function(){
		updateAuths(getModifiedAuths("3"), "org");
		updateAuths(getModifiedAuths("4"), "role");
		updateAuths(getModifiedAuths("5"), "group");
		updateAuths(getModifiedAuths("6"), "user");

		//含下级权限删除处理
		var item, dLevelCode, itemJ;
		for (var i in auths.org) {
			item = auths.org[i];
			if (item.hasProgeny == "1") {
				dLevelCode = item.dLevelCode;
				for (var j in auths.org) {
					itemJ = auths.org[j];
					if (itemJ.dLevelCode.indexOf(dLevelCode) == 0 && itemJ.dLevelCode.length > dLevelCode.length) {
						itemJ.hasProgeny = "0";
						itemJ.visitAuth = "0";
					}
				}
			}
		}

		var permissions = [];
		var auth, oAuth;
		for ( var key in auths) {
			if (key == "anon") {
				continue;
			}
			for ( var k in auths[key]) {
				auth = auths[key][k];
				oAuth = originalAuths[key][k];
				if (oAuth) {
					if (!(oAuth.hasProgeny == auth.hasProgeny && oAuth.visitAuth == auth.visitAuth)) {
						auth.resourceCode = id;
						permissions.push(auth);
					}
				}else{
					auth.resourceCode = id;
					permissions.push(auth);
				}
			}
		}

		return permissions;
	}
	/**
	 * 国际化
	 * @param code
	 * @returns {*}
	 */
	var getI18n = function(code){
		var i18n = $this.find("#tempo-app-permission-i18n");
		return i18n.attr("_" + code);
	}

	init();
});	